package mm.chenchen.modules.file.service.impl;

import lombok.extern.slf4j.Slf4j;
import mm.chenchen.common.utils.*;
import mm.chenchen.common.utils.MinioClientUtil;
import mm.chenchen.common.utils.MinioUtil;
import mm.chenchen.common.utils.PageUtils;
import mm.chenchen.common.utils.R;
import mm.chenchen.modules.file.entity.FileInfoEntity;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import mm.chenchen.modules.file.repository.FileInfoRepository;
import mm.chenchen.modules.file.service.FileInfoService;
import org.springframework.util.ObjectUtils;


@Service("fileInfoService")
@Slf4j
public class FileInfoServiceImpl  implements FileInfoService {

    @Autowired
    private FileInfoRepository repository;
    @Autowired
    private MinioClientUtil minioClientUtil;

    public R findAll() {
        PageUtils page=new PageUtils(repository.findAll(),repository.findAll().size(),1,1);
        return R.ok().put("page", page);    }

    public R findById(Long objId) {
        return R.ok().put("FileInfo",repository.findById(objId));
    }

    public R deleteById(Long objId) {
        FileInfoEntity fileInfoEntity=repository.findById(objId).get();
        if (!ObjectUtils.isEmpty(fileInfoEntity)){
            MinioUtil.delete(minioClientUtil.getMinioClient(), fileInfoEntity.getFileType(),fileInfoEntity.getMinioId());
            repository.deleteById(objId);
        }

        return R.ok();
    }

    public R save(FileInfoEntity data) {
        log.info("保存文件信息{}",data.toString());
        return R.ok().put("data",repository.save(data));
    }

    public R update(FileInfoEntity data) {
        return R.ok().put("data",repository.save(data));
    }
}